package com.micai.springboot.redis.config;

import com.micai.springboot.redis.consumer.CustomerInfoSubscriber;
import com.micai.springboot.redis.producer.CustomerInfoPublisher;
import com.micai.springboot.redis.producer.RedisCustomerInfoPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.GenericToStringSerializer;

import java.util.concurrent.Executors;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/9/28 14:49
 * @Description: Redis核心配置类
 */
@Configuration
@ComponentScan("com.micai.springboot.redis")
public class RedisConfig {

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        final RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
        return template;
    }

    @Bean
    MessageListenerAdapter messageListener() {
        return new MessageListenerAdapter(new CustomerInfoSubscriber());
    }

    @Bean
    RedisMessageListenerContainer redisContainer() {
        final RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(jedisConnectionFactory());
        container.addMessageListener(messageListener(), SmsTopic());
        container.setTaskExecutor(Executors.newFixedThreadPool(4));
        return container;
    }

    @Bean
    CustomerInfoPublisher redisPublisher() {
        return new RedisCustomerInfoPublisher(redisTemplate(), SmsTopic());
    }

    @Bean
    ChannelTopic SmsTopic() {
        return new ChannelTopic("pubsub:sms-channel");
    }
}
